import React, { Component, createRef, PureComponent } from 'react'
import { Badge, Button, Card, Col, Form, Input, Row, Select, Space, Table } from 'antd'
import { GenerateProductSyncInfo, PageQueryProduct } from '@/api/productInformation'
import { ERR_OK } from '@/utils/commons'
import { PoweroffOutlined, SyncOutlined, UpOutlined, DownOutlined } from '@ant-design/icons'
import { dataStatusTypesEnum } from '@/enums/common'
import { productTypes } from '@/enums/product'

export default class ProductSyncRC extends PureComponent {

  state = {
    expand: false,
    // searchFormData: {
    //   name: '', //  产品名
    //   code: '',//  产品编码
    //   productType: null,  //  el-select 匹配不到会显示一个奇怪的值,必须为null
    //   categoricalId: '',
    //   printTypeId: '',
    //   shopType: '',
    //   status: dataStatusTypesEnum['正常']  //  fixed
    // },

    data: [],
    pagination: {
      current: 1,
      pageSize: 10,
      total: 0
    },
    loading: false,
    columns: [
      // {
      //   title: 'Name',
      //   dataIndex: 'name',
      //   sorter: true,
      //   render: name => `${name.first} ${name.last}`,
      //   width: '20%'
      // },
      // {
      //   title: 'Gender',
      //   dataIndex: 'gender',
      //   filters: [
      //     { text: 'Male', value: 'male' },
      //     { text: 'Female', value: 'female' }
      //   ],
      //   width: '20%'
      // },

      // { 'dataIndex': 'ProductId', 'title': '产品ID' },
      {
        'dataIndex': 'ProductType',
        'title': '产品类型'
      }, { 'dataIndex': 'ProductName', 'title': '产品名' },

      // { 'dataIndex': 'quantity', 'title': '数量' },
      {
        'dataIndex': 'Code',
        'title': '编码'
      },
      // { 'dataIndex': 'CategoricalId', 'title': '产品分类ID' },
      {
        'dataIndex': 'CategoricalName',
        'title': '产品分类'
      },
      // { 'dataIndex': 'ProductShopType', 'title': '输出类型ID' },

      {
        'dataIndex': 'ProductShopTypeName',
        'title': '输出类型'
      }, { 'dataIndex': 'ProductSize', 'title': '产品尺寸' }, {
        'dataIndex': 'Describe',
        'title': '产品描述'
      }, { 'dataIndex': 'SizeDetailId', 'title': '标准尺寸' },

      // {
      //   'dataIndex': 'CreateBy',
      //   'title': '创建人'
      // }, { 'dataIndex': 'CreateTime', 'title': '创建时间' }, {
      //   'dataIndex': 'LastModifyBy',
      //   'title': '修改人'
      // }, { 'dataIndex': 'LastModifyTime', 'title': '修改时间' },

      { 'dataIndex': 'Status', 'title': '状态' },
      { 'dataIndex': 'ProductPrintTypeId', 'title': '打印类型' },
      { 'dataIndex': 'CutFilePath', 'title': '切割文件' },
      { 'dataIndex': 'Weight', 'title': '标准重量' },
      { 'dataIndex': 'SingleWeight', 'title': '单P重量' },

      { 'dataIndex': 'LastSyncDate', 'title': '最后同步' },
      { 'dataIndex': 'LastSyncUser', 'title': '同步人' },

      //        { 'dataIndex': 'SyncTimes', 'title': '同步次数' },
      {
        title: '操作',
        key: 'operation',
        fixed: 'right',
        width: 100,
        render: (text, record, idx) => {
          const SyncBtn = (<Button onClick={async() => {
            await this.syncProduct(text, record, idx)
          }} icon={<SyncOutlined/>}
                                   shape={'round'} size={'middle'} type={'primary'}>
            同步
          </Button>)
          return (
            record['SyncTimes'] ? <Badge count={record['SyncTimes']}>
              {SyncBtn}
            </Badge> : <>{SyncBtn}</>
          )
        }
      }

    ].map(v => ({ ...v, align: 'center' }))

  }
  searchFormRef = createRef()

  async syncProduct(text, record, idx) {
    console.log(text, record, idx)
    try {
      const { Code, Result } = await GenerateProductSyncInfo(Array.of(record.ProductId))
      if (Code === ERR_OK) {
        console.log('sync suc')
      } else {
        console.log('sync error')
      }
    } catch (e) {
      console.log(e)
    }
  }

  async getData({ current, pageSize, ...searchFormData } = {}) {

    console.log(current, pageSize)

    // const { pagination: { current, pageSize } } = this.state
    try {
      this.setState({ loading: true })
      const { Code, Result: { CurrentPage, RecordCount, Rows } = {} } = await PageQueryProduct({
        ...searchFormData,
        status: dataStatusTypesEnum['正常'], //  fixed
        pageSize,
        pageNum: current

        //  同步状态 ????
      })
      if (Code === ERR_OK) {
        this.setState({
          data: Rows,
          pagination: {
            ...this.state.pagination,
            current: CurrentPage,
            total: RecordCount
          }

        })
      } else {
        console.log('get error')
      }
    } catch (e) {
      console.log(e)
      console.log('get error')
    } finally {
      this.setState({ loading: false })
    }

  }

  handleTableChange = (pagination) => {
    this.getData({ ...pagination }).then(r => void console.log())
  }

  componentDidMount() {
    this.getData().then(r => void console.log())
  }

  onFinish = (values) => {
    ;(async() => {
      console.log(values)
      console.log(this.state)
      const { pagination } = this.state
      await this.getData({ ...values, ...pagination })
    })()
  }

  setExpand = (expand) => {
    this.setState({
      expand
    })
  }

  getFields = () => {
    const { expand } = this.state

    const formItemList =
      [
        <Col span={8} key={'name'}>
          <Form.Item label="产品名" name="name">
            <Input/>
          </Form.Item>
        </Col>,
        <Col span={8} key={'code'}>
          <Form.Item label="产品编码" name="code">
            <Input/>
          </Form.Item>
        </Col>,
        <Col span={8} key={'productType'}>
          <Form.Item label="产品类型" name="productType">
            <Select>
              {productTypes.map(({ label, value }) => <Select.Option value={value}>
                {label}
              </Select.Option>)}
            </Select>
          </Form.Item>
        </Col>,

        <Col span={8} key={'categoricalId'}>
          <Form.Item label="类目" name="categoricalId">
            <Select>
              <Select.Option value="demo">Demo</Select.Option>
            </Select>
          </Form.Item>
        </Col>,
        <Col span={8} key={'printTypeId'}>
          <Form.Item label="打印类型" name="printTypeId">
            <Select>
              <Select.Option value="demo">Demo</Select.Option>
            </Select>
          </Form.Item>
        </Col>,
        <Col span={8} key={'shopType'}>
          <Form.Item label="输出类型" name="shopType">
            <Select>
              <Select.Option value="demo">Demo</Select.Option>
            </Select>
          </Form.Item>
        </Col>

      ]
    if (!expand) {
      return formItemList.slice(0, 3)
    }
    return formItemList
  }

  renderTable() {
    const { data, pagination, loading, columns } = this.state
    return (<Table
      size="middle"
      rowKey={(record) => record.ProductId}
      columns={columns}
      dataSource={data}
      pagination={pagination}
      loading={loading}
      onChange={this.handleTableChange}
    />)
  }

  renderSearchForm() {
    const { expand } = this.state
    return (<>
      <Form
        name="advanced_search"
        // ref={el=>this.searchFormRef=el}
        ref={this.searchFormRef}
        onFinish={this.onFinish}
      >
        <Row gutter={24}>{this.getFields()}</Row>
        <Row>
          <Col span={24} style={{ textAlign: 'right' }}>
            <Button type="primary" htmlType="submit">
              搜索
            </Button>
            <Button
              style={{ margin: '0 8px' }}
              onClick={() => {
                this.searchFormRef.current.resetFields()
              }}
            >
              清空
            </Button>
            <a
              style={{ fontSize: 12 }}
              onClick={() => {
                this.setExpand(!expand)
              }}
            >
              {expand ? <span><UpOutlined/>收起</span> : <span><DownOutlined/>展开</span>}
            </a>
          </Col>
        </Row>
      </Form>
    </>)
  }

  render() {
    return (
      <div style={{ padding: '20px' }}>
        <Card style={{ marginBottom: '20px' }}>
          {this.renderSearchForm()}
        </Card>
        <Card>
          {this.renderTable()}
        </Card>
      </div>
    )
  }
}
